package com.itheima.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;

import com.itheima.entry.Result;
import com.itheima.pojo.Setmeal;
import com.itheima.service.MemberService;
import com.itheima.service.OrderService;
import com.itheima.service.SetmealService;
import com.itheima.utils.DateUtil;
import com.itheima.utils.RedisUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;



import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.*;

@RestController
@RequestMapping("/operatingReport")
public class OperatingReportController {

    @Reference
    private MemberService memberService;//执行会员信息查找

    @Reference
    private OrderService orderService;//查找预约数,到诊数

    @Reference
    private SetmealService setmealService;//查找热门套餐






    /**
     * 获取套餐数据
     */


    /**
     * 获取运营数据
     *
     */
    @GetMapping("/getOperatingReportsData")
    public Result getOperatingReportsData() throws Exception {

//        Result result =null;
        String formatDate = DateUtil.formatDate(new Date());
//        result = RedisUtil.get("date:" + formatDate);
//        if (result == null) {


            ExecutorService executorService = Executors.newFixedThreadPool(12);

            Future<List<Map>> setmealList =executorService.submit(() -> {

                //查询所有的订单
                int count = orderService.count();
                //获取热门套餐
                List<Map>  setmealList1 = setmealService.findHotSetmeal();
                for (Map setmeal : setmealList1) {
                    Long setmeal_count = (Long) setmeal.get("setmeal_count");

                    setmeal.put("proportion",(new BigDecimal((setmeal_count * 1.0) / count).multiply(new BigDecimal(100))).setScale(2, BigDecimal.ROUND_HALF_UP)+"%");
                }

                return setmealList1;
            });
            System.out.println("setmealList = " + setmealList);



            int thisweek = DateUtil.getWeekNum(new Date());//本周
            String thismonth = DateUtil.formatDate(new Date(),"MM");//本月
            //获取今日新增会员数量
            Future< Integer> todayNewMember =executorService.submit(() -> {
                return memberService.findTodayNewMember(formatDate);
            });
            //获取会员总数量
            Future< Integer> totalMember =executorService.submit(() -> {
                return memberService.count();
            });

            //获取本周新增会员数量
            Future< Integer> thisWeekNewMember =executorService.submit(() -> {
                return memberService.findThisWeekNewMember(thisweek);
            });

            //获取本月新增会员数量
            Future< Integer> thisMonthNewMember =executorService.submit(() -> {
                return memberService.findThisMonthNewMember(thismonth);
            });

            //获取本日预约数量
            Future< Integer> todayOrderNumber =executorService.submit(() -> {
                return orderService.findTodayOrderNumber(formatDate);
            });

            //获取本日到诊数量
            Future< Integer> todayVisitsNumber =executorService.submit(() -> {
                return orderService.findTodayVisitsNumber(formatDate);
            });

            //获取本周预约数量
            Future< Integer> thisWeekOrderNumber =executorService.submit(() -> {
                return orderService.findThisWeekOrderNumber(thisweek);
            });
            //获取本周到诊数量
            Future< Integer> thisWeekVisitsNumber =executorService.submit(() -> {
                return orderService.findThisWeekVisitsNumber(thisweek);
            });

            //获取本月预约数量
            Future< Integer> thisMonthOrderNumber =executorService.submit(() -> {
                return orderService.findThisMonthOrderNumber(thismonth);
            });
            //获取本月到诊数量
            Future< Integer> thisMonthVisitsNumber =executorService.submit(() -> {
                return orderService.findThisMonthVisitsNumber(thismonth);
            });

            Map<String, Object> map = new HashMap<String, Object>();
            map.put("reportDate", formatDate);//报表日期
            map.put("todayNewMember", todayNewMember.get());//今日新增会员数
            map.put("totalMember", totalMember.get());//总会员数
            map.put("thisWeekNewMember",thisWeekNewMember.get());//本周新增会员数
            map.put("thisMonthNewMember",thisMonthNewMember.get());//本月新增会员数

            map.put("todayOrderNumber", todayOrderNumber.get());//今日预约数
            map.put("todayVisitsNumber", todayVisitsNumber.get());//今日到诊数

            map.put("thisWeekOrderNumber",thisWeekOrderNumber.get());//本周预约数
            map.put("thisWeekVisitsNumber", thisWeekVisitsNumber.get());//本周到诊数

            map.put("thisMonthOrderNumber", thisMonthOrderNumber.get());//本月预约数
            map.put("thisMonthVisitsNumber", thisMonthVisitsNumber.get());//本月到诊数

            map.put("hotSetmeal", setmealList.get());//前5个热门套餐
            Result result = new Result(map);
//            RedisUtil.set("date:"+formatDate,result,2, TimeUnit.HOURS);
//        }
        return result;
    }

    @GetMapping("/downLoad")
    public  void downLoad(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("text/html;charset=utf-8");
        Result result=getOperatingReportsData();
        Map map = (Map) result.getData();
        TemplateExportParams params = new TemplateExportParams("tmp/report_template.xlsx");
        Workbook workbook = ExcelExportUtil.exportExcel(params, map);

        String filename="运营报表.xlsx";
        String encodeFilename = URLEncoder.encode(filename, "UTF-8");
        //7.第一个头：告知浏览器下载的文件在tomcat服务器中类型
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        //8.第二个头：告知浏览器以附件形式下载
        response.setHeader("content-disposition", "attachment;filename=" + encodeFilename);
        OutputStream os = response.getOutputStream();

        workbook.write(os);
        os.close();
    }


}
